package com.atguigu.gulimall.order.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.to.MemberEntityVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberEntityVo> threadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 放行白名单
        boolean match = new AntPathMatcher().match("/order/order/status/**", request.getRequestURI());
        if (match) {
            return true;
        }

        HttpSession session = request.getSession();
        Object userInfo = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (userInfo != null) {
            // 已经登录过
            MemberEntityVo info = (MemberEntityVo) userInfo;
            threadLocal.set(info);
            return true;
        } else {
            // 没登陆，就去登录
            response.sendRedirect("http://auth.gulimall.com/login.html?originUrl=http://order.gulimall.com" + request.getRequestURI());
            return false;
        }
    }
}
